<template>
  <div class="app-container">
    <el-row :gutter="20">
      <!-- 目录树 -->
      <el-col :lg="4" :md="5" :sm="6" :xs="24" class="mb-[12px] !pr-0">
        <mdmpersoninfo-tree
          ref="organizationTree"
          v-model="searchParam.departmentId"
          @node-click="search"
        />
      </el-col>
      <el-col :lg="20" :md="19" :sm="18" :xs="24">
        <div class="search-container">
          <el-form :model="searchParam" :inline="true" label-width="70px">
            <el-form-item label="员工号">
              <el-input
                v-model="searchParam.empNo"
                placeholder="请输入员工号"
                clearable
                @keyup.enter="search"
              />
            </el-form-item>
            <el-form-item label="姓名">
              <el-input
                v-model="searchParam.personName"
                placeholder="请输入姓名"
                clearable
                @keyup.enter="search"
              />
            </el-form-item>
            <el-form-item label="岗位">
              <el-select
                v-model="searchParam.post"
                placeholder="请选择岗位"
                clearable
                style="width: 100%"
              >
                <el-option
                  v-for="item in dictionaryStore.filterDictList('PostType')"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                />
              </el-select>
            </el-form-item>
            <el-form-item label="人员状态" label-width="70px">
              <el-select
                v-model="searchParam.personStatus"
                placeholder="请选择人员状态"
                clearable
              >
                <el-option
                  v-for="item in dictionaryStore.filterDictList('personStatus')"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                />
              </el-select>
            </el-form-item>
            <el-form-item>
              <el-button type="primary" @click="search"
                ><i-ep-search />搜索</el-button
              >
              <el-button @click="reset"><i-ep-refresh />重置</el-button>
            </el-form-item>
          </el-form>
        </div>

        <el-card shadow="never" class="table-container">
          <template #header>
            <el-button type="primary" @click="openDialog()"
              ><i-ep-plus />新增</el-button
            >
            <el-button
              type="danger"
              plain
              :disabled="ids.length === 0"
              @click="handleTableDelete()"
              ><i-ep-delete />删除</el-button
            >
            <el-button
              class="ml-3"
              type="primary"
              @click="
                useDownload(
                  '/mdm/mdmpersoninfo/export',
                  '人员信息',
                  searchParam
                )
              "
            >
              <template #icon><i-ep-download /></template>导出</el-button
            >
            <el-button type="primary" @click="excelBoxOpen">导入 </el-button>
            <el-dialog
              :close-on-click-modal="false"
              title="人员信息数据导入"
              v-model="excelBox"
              width="555px"
            >
              <div>
                <el-button
                  @click="
                    useDownload(
                      '/mdm/mdmpersoninfo/exportTemp',
                      '人员信息上传模板',
                      searchParam
                    )
                  "
                >
                  <template #icon>
                    <i-ep-download />
                  </template>
                  人员信息上传模板下载
                </el-button>
              </div>
              <div style="margin-top: 10px">
                <input
                  class="crop-input"
                  type="file"
                  name="image"
                  accept="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"
                  ref="onload_exl"
                  @change="getfilepath"
                />
                <el-button
                  @click="upload"
                  :disabled="uploadBtn"
                  style="cursor: pointer"
                  >上传</el-button
                >
              </div>
            </el-dialog>
          </template>

          <el-table
            ref="dataTableRef"
            v-loading="loading"
            :data="table1"
            highlight-current-row
            border
            @selection-change="handleSelectionChange"
          >
            <el-table-column type="selection" width="55" align="center" />
            <el-table-column
              label="员工号"
              prop="empNo"
              min-width="150"
              show-overflow-tooltip
            />
            <el-table-column
              label="姓名"
              prop="personName"
              min-width="100"
              show-overflow-tooltip
            />
            <el-table-column
              label="性别"
              prop="sex"
              min-width="100"
              show-overflow-tooltip
              align="center"
            >
              <template #default="scope">
                {{ useDictionary("SexType", scope.row.sex) }}
              </template>
            </el-table-column>

            <el-table-column
              label="学历"
              prop="education"
              min-width="100"
              show-overflow-tooltip
              align="center"
            >
              <template #default="scope">
                <span>{{
                  useDictionary("EducationType", scope.row.education)
                }}</span>
              </template>
            </el-table-column>

            <el-table-column
              label="所在部门"
              prop="departmentId"
              min-width="160"
              show-overflow-tooltip
              align="center"
            >
              <template #default="scope">
                {{ scope.row.departmentName }}
              </template>
            </el-table-column>
            <el-table-column
              label="岗位"
              prop="post"
              min-width="100"
              show-overflow-tooltip
              align="center"
            >
              <template #default="scope">
                <span>{{ useDictionary("PostType", scope.row.post) }}</span>
              </template>
            </el-table-column>
            <el-table-column
              label="人员状态"
              prop="personStatus"
              min-width="100"
              show-overflow-tooltip
              align="center"
            >
              <template #default="scope">
                <span>{{
                  useDictionary("personStatus", scope.row.personStatus)
                }}</span>
              </template>
            </el-table-column>

            <el-table-column
              label="创建时间"
              prop="createTime"
              min-width="160"
              show-overflow-tooltip
              align="center"
            />
            <el-table-column
              label="创建人"
              prop="createdUserName"
              min-width="100"
              show-overflow-tooltip
              align="center"
            />
            <el-table-column
              label="修改时间"
              prop="lastUpdateTime"
              min-width="160"
              show-overflow-tooltip
              align="center"
            />
            <el-table-column
              label="修改人"
              prop="lastUpdatedUserName"
              min-width="100"
              show-overflow-tooltip
              align="center"
            />

            <el-table-column
              fixed="right"
              label="操作"
              width="240"
              align="center"
            >
              <template #default="scope">
                <el-button
                  type="primary"
                  size="small"
                  link
                  @click="openDialogdetail(scope.row)"
                  ><i-ep-search />
                  查看
                </el-button>
                <el-button
                  type="primary"
                  size="small"
                  link
                  @click="openDialog(scope.row)"
                  ><i-ep-edit />编辑</el-button
                >
                <el-button
                  type="primary"
                  size="small"
                  link
                  @click="handleTableDelete(scope.row.id)"
                  ><i-ep-delete />删除</el-button
                >
              </template>
            </el-table-column>
          </el-table>

          <el-pagination
            :background="true"
            :current-page="pageable.pageNum"
            :page-size="pageable.pageSize"
            :page-sizes="[10, 25, 50, 100]"
            :total="pageable.total"
            layout="total, sizes, prev, pager, next, jumper"
            class="mt-[20px]"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
          />
        </el-card>

        <mdmpersoninfo-edit
          :visible="addDialog.visible"
          :title="addDialog.title"
          :departmentId="addDialog.departmentId"
          :data="addDialog.data"
          @reset-table="(id:string) => (id?.length ? getTableList() : reset())"
          :is-readonly="addDialog.readvisible"
          @change-visible="changeVisible"
        />
      </el-col>
    </el-row>
  </div>
</template>

<script setup lang="ts">
import { useTable, useDownload, useDictionary } from "@/utils/useTable";
import request from "@/utils/request";
import { useDictStoreHook } from "@/store/modules/dictionary"; // 引入
const dictionaryStore = useDictStoreHook();

defineOptions({
  name: "MDMMDMPERSONINFO",
  inheritAttrs: false,
});

// 请求参数
const requestApi = "/mdm/mdmpersoninfo/queryByPage";

// 是否需要分页
const pagination = true;

const initParam = {};

// 初始化搜索参数数据
const searchParamInit = {
  empNo: "",
  personName: "",
  post: "",
  personStatus: "",
  departmentId: "",
};

const deleteParam = {
  api: "/mdm/mdmpersoninfo/delete",
  data: {},
};

// 数据请求错误后处理
function requestError() {}

const table1 = ref([]);

const plantListLable: any = ref([]);
const dataCallBack = ref(async (res: any) => {
  const plantList = await request({
    url: "system/sysOrganization/getList",
    method: "post",
    data: {},
  });

  plantListLable.value = plantList.data;
  // for (let j = 0; j < res.length; j++) {
  //   for (let i = 0; i < plantListLable.value.length; i++) {
  //     if (res[j].departmentId == plantListLable.value[i].id) {
  //       res[j].departmentId = plantListLable.value[i].organizationCode;
  //     }
  //   }
  // }

  res.forEach((item) => {
    plantListLable.value.forEach((item1) => {
      if (item.departmentId == item1.id) {
        item.departmentId = item1.organizationCode;
      }
    });
    // for (let i = 0; i < plantListLable.value.length; i++) {
    //   if (item.departmentId == plantListLable.value[i].id) {
    //     item.departmentId = plantListLable.value[i].organizationCode;
    //   }
    // }
  });
  table1.value = res;

  return table1.value;
}); // 无需二次数据处理&不传赞数也行

// 表格操作 Hooks
const {
  tableData,
  pageable,
  searchParam,
  ids,
  getTableList,
  search,
  reset,
  handleSizeChange,
  handleCurrentChange,
  handleSelectionChange,
  handleTableDelete,
  loading,
}: any = useTable(
  requestApi,
  initParam,
  searchParamInit,
  pagination,
  dataCallBack.value,
  requestError,
  deleteParam
);

onMounted(() => {
  getTableList();
});

const addDialog: any = reactive<DialogOption>({
  visible: false,
  readvisible: false,
  title: "",
  departmentId: "",
  data: {},
});

// 查询详情
async function getInfo(id: string) {
  request({
    url: `/mdm/mdmpersoninfo/get/${id}`,
    method: "get",
  })
    .then((data) => {
      addDialog.data = data.data;
      addDialog.visible = true;
    })
    .catch((res) => {
      console.log(res);
    });
}

/** 打开人员信息表单弹窗 */
function openDialog(roleObj?: Object) {
  if (roleObj) {
    addDialog.title = "修改人员信息";
    getInfo(roleObj.id);
  } else {
    addDialog.title = "新增人员信息";
    addDialog.visible = true;
    addDialog.departmentId = searchParam.value.departmentId;
    console.log(addDialog.departmentId);
  }
  addDialog.readvisible = false;
}

/** 打开人员信息表单弹窗 详情 */
function openDialogdetail(roleObj?: any) {
  addDialog.title = "人员信息详情";
  getInfo(roleObj.id);
  addDialog.readvisible = true;
}

function changeVisible(value: boolean) {
  addDialog.visible = value;
  if (!value) {
    addDialog.data = {};
  }
}

// 导入excel
const uploadApi = "/mdm/mdmpersoninfo/upload";
const excelBox = ref(false);
const uploadBtn = ref(false);
const uploadFile = ref("");
const fileName = ref("");

function excelBoxOpen() {
  excelBox.value = true;
}

function getfilepath(e: any) {
  const file = e.target.files[0];
  fileName.value = file.name;
  uploadFile.value = file;
  uploadBtn.value = false;
}

function upload() {
  if (!uploadFile.value) {
    ElMessage({
      type: "warning",
      message: "请选择文件！",
    });
    return;
  }

  let formdata = new FormData();
  formdata.append("file", uploadFile.value);
  let config = { headers: { "Content-Type": "multipart/form-data" } };
  request
    .post(uploadApi, formdata, config)
    .then((res) => {
      ElMessage({
        type: "success",
        message: "上传成功！",
      });

      excelBox.value = false;
      uploadBtn.value = true;
      search();
    })
    .catch((error) => {
      console.log(error);
    });
}
</script>
